package com.alice.router.guigu;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author alice
 * @date 2022/1/10
 * @apiNote
 */
public class FutureTaskTest {
    public static final int MAX_TURN = 5;
    public static final int COMPUTE_TIMES = 100000000;

    public static String getCurThreadName(){
        return Thread.currentThread().getName();
    }

    static class ReturnableTask implements Callable<String>{

        @Override
        public String call() throws Exception {
            long startTime = System.currentTimeMillis();
            System.out.println(getCurThreadName()+"线程运行开始");
            Thread.sleep(1000);

            for (int i = 0; i < COMPUTE_TIMES; i++) {
                int j = i * 10000;
            }
            long used = System.currentTimeMillis() - startTime;
            System.out.println(getCurThreadName() + " 线程运行结束.");
            return ""+used;
        }
    }

    public static void main(String args[]) throws InterruptedException {
        ReturnableTask task=new ReturnableTask();//③
        FutureTask<String> futureTask = new FutureTask<String>(task);//④
        Thread thread = new Thread(futureTask, "returnableThread");//⑤
        thread.start();//⑥
        Thread.sleep(500);
        System.out.println(getCurThreadName() + " 让子弹飞一会儿.");
        System.out.println(getCurThreadName() + " 做一点自己的事情.");
        for (int i = 0; i < COMPUTE_TIMES / 2; i++) {
            int j = i * 10000;
        }
        System.out.println(getCurThreadName() + " 获取并发任务的执行结果.");
        try {
            System.out.println(thread.getName()+"线程占用时间："
                    + futureTask.get());//⑦
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(getCurThreadName() + " 运行结束.");
    }
}
